package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result selectType() {
        //查询redis中是否存在shopType
        //因为从redis中取出的是json字符串，所以虽然写了string但是要记住这是json字符串
        String shopTypeStr = stringRedisTemplate.opsForValue().get("cache:shopType:");
        //有，返回数据
        if(StrUtil.isNotBlank(shopTypeStr)){
            List<ShopType> shopType = JSONUtil.toList(shopTypeStr, ShopType.class);
            return Result.ok(shopType);
        }
        //没有，去数据库中查询
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //保存数据到缓存中，再返回
        String jsonStr = JSONUtil.toJsonStr(shopTypes);
        stringRedisTemplate.opsForValue().set("cache:shopType:",jsonStr);
        return Result.ok(shopTypes);
    }
}
